<template>
   <PlayGround v-if="$store.state.pk.status==='playing'"></PlayGround>
    <!-- <h1>aaaa</h1> -->
  <match-ground v-if="$store.state.pk.status==='matching'"></match-ground>
  <result-board v-if="$store.state.pk.loser!='none'"></result-board>
</template>

<script setup>
import PlayGround from '../../components/PlayGround.vue'
import MatchGround from '../../components/MatchGround'
import {onMounted,onUnmounted} from "vue";
import {useStore} from "vuex";
import ResultBoard from "@/components/ResultBoard";


    let socket =null;
    const store=useStore();
      store.commit("updateLoser", "none");
    const socketUrl=`ws://127.0.0.1:3000/websocket/${store.state.user.token}`;

// eslint-disable-next-line no-unused-vars

    onMounted(()=>{
      //测试
      store.commit("updateOpponent",{
        username:"我的对手",
        photo:"https://cdn.acwing.com/media/article/image/2022/08/09/1_1db2488f17-anonymous.png"
      })

      socket=new WebSocket(socketUrl);

      socket.onopen=()=>{
        console.log("连接建立！")
        store.commit("updateSocket",socket);
      }

      socket.onmessage= msg=>{
        const data=JSON.parse(msg.data);
        if(data.event==="start-matching"){  //匹配成功
          store.commit("updateOpponent",{
            username:data.opponent_username,
            photo:data.opponent_photo,
          });

          setTimeout(()=>{
            store.commit("updateStatus", "playing");
          },200);
          store.commit("updateGame",data.game);
        }else if (data.event === "move") {
          const game=store.state.pk.gameObject;
          const [snake0,snake1]=game.snakes;
          snake0.set_direction(data.a_direction);
          snake1.set_direction(data.b_direction);

        }else if (data.event === "result") {
          console.log("后端的结果： ",data);
          const game=store.state.pk.gameObject;
          const [snake0,snake1]=game.snakes;
          if (data.loser === "all" || data.loser === "A") {
            snake0.status = "die";
          }
          if (data.loser === "all" || data.loser === "B") {
            snake1.status = "die";
          }
          store.commit("updateLoser",data.loser)


        }
      }

      socket.onclose=()=>{
        console.log("断开连接！")
      }

    });


    onUnmounted(()=>{
      socket.close();
      store.commit("updateStatus","matching")
    })



</script>

<style scoped>
</style>
